import React, {Component, Fragment} from 'react'
import {render} from "react-dom"
import axios from 'axios'

export default class Signin extends Component {
  constructor(props) {
    super(props)
    this.state = {
      'username': '',
      'password': '',
      error: ''
    }
  }

  onChangeUsername = (e) => {
    this.setState({username: e.target.value})
  }

  onChangePassword = (e) => {
    this.setState({password: e.target.value})
  }

  onSubmit = (e) => {
    e.preventDefault();
    axios.post('http://127.0.0.1:8000/auth/jwt/create/', this.state).then((res) => {
      if (res.status === 200) {
        console.log(res.data)
        window.localStorage.setItem('access_token', res.data.access);
        // this.props.history.push('/index')
        axios.get('http://127.0.0.1:8000/auth/users/me/', {
          'headers': {
            'Authorization': 'Bearer ' + res.data.access
          }
        }).then((res) => {
          if (res.status === 200) {
            window.localStorage.setItem('id', res.data.id);
            window.localStorage.setItem('username', res.data.username);
            window.location.href = 'http://127.0.0.1:3000'
          }
        });

      }
    }).catch((err) => {
      if (err.response.data.detail == 'No active account found with the given credentials') {
        this.setState({error: '尚未注册或密码错误！'})
      }
    });

    console.log('submmmit');
  }

  render() {
    return (
      <form onSubmit={
        this.onSubmit
      }>

        <div class="form-group">
          <label for="exampleInputEmail1">姓名</label>
          <input type="text"
            value={
              this.state.username
            }
            onChange={
              this.onChangeUsername
            }
            name="username"
            class="form-control"
            id="exampleInputEmail1"
            aria-describedby="emailHelp"
            placeholder="请输入你的姓名"/>
        </div>
        <div class="form-group">
          <label for="exampleInputPassword1">密码</label>
          <input type="password"
            value={
              this.state.password
            }
            onChange={
              this.onChangePassword
            }
            name="password"
            class="form-control"
            id="exampleInputPassword1"
            placeholder="请输入你的密码"/></div>

        {/* <div class="form-check">
          <input type="checkbox" class="form-check-input" id="exampleCheck1"/>
          <label class="form-check-label" for="exampleCheck1">Check me out</label>
        </div> */}
        <button type="submit" class="btn btn-primary">登录</button>
          <br />
          <br />
        <Fragment>{
          this.state.error ? <span className="alert alert-danger">
            {
            this.state.error
          }</span> : null
        }</Fragment>
      </form>
    )
  }

}
